#include "My_Socket.hpp"
#include <iostream>
#include <memory>
#include <functional>
#include "log.hpp"
#include <sys/types.h>
#include <sys/wait.h>
// TcpServer只负责进行流式的IO，不对协议进行任何处理
// using  tcphander=std::function<>
namespace TcpServerModule
{
  using namespace SockModel;
  using namespace LogModel;
  using tcphandler_t = std::function<bool(SockPtr, InetAdrr)>;
  class TcpServer
  {
  public:
    TcpServer(int port) : _listenfp(std::make_unique<TcpSocket>()),
                          _isrunning(false), _port(port)
    {
    }
    void InitSever(tcphandler_t handler)
    {
      _handler = handler;
      _listenfp->SocketInit(_port);
    }
    void Loop()
    {
      _isrunning = true;
      while (_isrunning)
      {
        InetAdrr client;
        SockPtr sockfd = _listenfp->AcceptOrDie(client);
        if (sockfd == nullptr)  
          continue;

        //  IO处理
        LOG(LogLevel::DEBUG) << "get a new client, info is: " << client.IP() << ": " << client.Port();

        pid_t pid = fork();
        if (pid == 0)
        {
          //子进程不用listenfd
          _listenfp->Close();
          if (fork() > 0)
            exit(0);
          // 要执行的回调方法
          _handler(sockfd, client);
          exit(0);
        }
        //父进程不用Acceptfd
        sockfd->Close();
        pid_t rid = waitpid(pid, nullptr, 0);
        if (rid < 0)
        {
          LOG(LogLevel::WARNING) << "wait error";
        }
      }
      _isrunning = false;
    }

    ~TcpServer()
    {
      _listenfp->Close();
    }

  private:
    std::unique_ptr<Socket> _listenfp;
    tcphandler_t _handler;
    bool _isrunning;
    int _port;
  };

}
